import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Input,
  DatePicker,
  Select,
  Drawer,
  Statistic,
  Form,
  Modal,
  InputNumber,
  message,
  Row,
  Col,
  Typography,
  Avatar,
  Tabs,
} from 'antd';
import {
  ReloadOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  RollbackOutlined,
  ExclamationCircleOutlined,
  DollarOutlined,
  CalendarOutlined,
  UserOutlined,
  FileTextOutlined,
  BarChartOutlined,
  TableOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { getOrders, getOrderDetail, refundOrder, getOrderStatistics } from '../../services/orders';
import useUser from '../../hooks/useUser';
import OrderAnalytics from './OrderAnalytics';
import './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Text, Title } = Typography;
const { confirm } = Modal;
const { Search } = Input;

const statusColors = {
  paid: 'green',
  refunded: 'volcano',
};

const statusLabels = {
  paid: '已支付',
  refunded: '已退款',
};

const paymentMethodLabels = {
  wechat: '微信支付',
  alipay: '支付宝',
  bank: '银行转账',
  cash: '现金支付',
  credit_card: '信用卡',
};

const Orders = () => {
  // 获取登录用户信息
  const { teacherId } = useUser();
  
  // 订单列表状态
  const [orders, setOrders] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    status: undefined,
    searchTerm: '',
    dateRange: null,
  });
  
  // 订单详情状态
  const [currentOrder, setCurrentOrder] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  
  // 退款表单
  const [refundForm] = Form.useForm();
  const [refundModalVisible, setRefundModalVisible] = useState(false);
  const [refundLoading, setRefundLoading] = useState(false);
  
  // 统计数据
  const [statistics, setStatistics] = useState({
    total_orders: 0,
    paid_orders: 0,
    refunded_orders: 0,
    total_sales: 0,
    total_refunds: 0,
    net_income: 0,
  });
  const [statsLoading, setStatsLoading] = useState(false);
  
  // 添加Tab切换状态
  const [activeKey, setActiveKey] = useState('orders');
  
  // 获取订单列表
  const fetchOrders = useCallback(async (page = pagination.current, pageSize = pagination.pageSize, filterParams = filters) => {
    setLoading(true);
    try {
      const params = {
        page,
        limit: pageSize,
        teacherId,
        ...filterParams.status ? { status: filterParams.status } : {},
        ...filterParams.searchTerm ? { searchTerm: filterParams.searchTerm } : {},
        ...filterParams.dateRange ? {
          dateFrom: dayjs(filterParams.dateRange[0]).format('YYYY-MM-DD'),
          dateTo: dayjs(filterParams.dateRange[1]).format('YYYY-MM-DD'),
        } : {},
      };
      
      const res = await getOrders(params);
      setOrders(res.data);
      setPagination(prev => ({
        ...prev,
        current: page,
        pageSize,
        total: res.pagination.total,
      }));
    } catch (error) {
      console.error('获取订单列表失败:', error);
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  }, [teacherId]);
  
  // 获取订单统计数据
  const fetchStatistics = useCallback(async (filterParams = filters) => {
    setStatsLoading(true);
    try {
      const params = {
        teacherId,
        ...filterParams.dateRange ? {
          dateFrom: dayjs(filterParams.dateRange[0]).format('YYYY-MM-DD'),
          dateTo: dayjs(filterParams.dateRange[1]).format('YYYY-MM-DD'),
        } : {},
      };
      
      const res = await getOrderStatistics(params);
      setStatistics(res.data);
    } catch (error) {
      console.error('获取订单统计数据失败:', error);
      message.error('获取订单统计数据失败');
    } finally {
      setStatsLoading(false);
    }
  }, [teacherId]);
  
  // 初始加载
  useEffect(() => {
    if (teacherId) {
      fetchOrders();
      fetchStatistics();
    }
  }, [fetchOrders, fetchStatistics, teacherId]);
  
  // 表格分页变化
  const handleTableChange = (pagination) => {
    fetchOrders(pagination.current, pagination.pageSize, filters);
  };
  
  // 查看订单详情
  const viewOrderDetail = async (orderId) => {
    setDetailLoading(true);
    try {
      const res = await getOrderDetail(orderId, { teacherId });
      setCurrentOrder(res.data);
      setDetailVisible(true);
    } catch (error) {
      console.error('获取订单详情失败:', error);
      message.error('获取订单详情失败');
    } finally {
      setDetailLoading(false);
    }
  };
  
  // 关闭详情抽屉
  const closeDetail = () => {
    setDetailVisible(false);
    setCurrentOrder(null);
  };
  
  // 处理退款
  const handleRefund = (order) => {
    setCurrentOrder(order);
    refundForm.setFieldsValue({
      refund_amount: order.amount ? Number(order.amount) : 0,
      refund_reason: '',
    });
    setRefundModalVisible(true);
  };
  
  // 提交退款
  const submitRefund = async () => {
    try {
      const values = await refundForm.validateFields();
      setRefundLoading(true);
      values.teacherId = teacherId;
      
      await refundOrder(currentOrder.id, values);
      message.success('退款申请提交成功');
      setRefundModalVisible(false);
      fetchOrders();
      fetchStatistics();
    } catch (error) {
      console.error('提交退款申请失败:', error);
      message.error('提交退款申请失败');
    } finally {
      setRefundLoading(false);
    }
  };
  
  // 确认退款弹窗
  const showRefundConfirm = () => {
    confirm({
      title: '确认退款',
      icon: <ExclamationCircleOutlined />,
      content: '退款操作不可撤销，是否确认处理退款？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        submitRefund();
      },
    });
  };
  
  // 处理筛选变化
  const handleFilterChange = (key, value) => {
    const newFilters = {
      ...filters,
      [key]: value,
    };
    setFilters(newFilters);
    
    // 如果搜索框被清空，立即触发搜索
    if (key === 'searchTerm' && value === '') {
      fetchOrders(1, pagination.pageSize, newFilters);
      fetchStatistics(newFilters);
      return;
    }
    
    // 只对搜索框进行特殊处理，其他筛选项立即触发
    if (key === 'searchTerm') {
      // 不立即触发搜索
      return;
    }
    
    // 自动应用筛选条件
    fetchOrders(1, pagination.pageSize, newFilters);
    fetchStatistics(newFilters);
  };
  
  // 处理搜索框搜索触发
  const handleSearch = () => {
    fetchOrders(1, pagination.pageSize, filters);
    fetchStatistics(filters);
  };
  
  // 重置筛选
  const resetFilters = () => {
    const emptyFilters = {
      status: undefined,
      searchTerm: '',
      dateRange: null,
    };
    setFilters(emptyFilters);
    
    // 自动应用重置后的筛选条件
    fetchOrders(1, pagination.pageSize, emptyFilters);
    fetchStatistics(emptyFilters);
  };
  
  // 表格列配置
  const columns = [
    {
      title: '订单编号',
      dataIndex: 'order_no',
      key: 'order_no',
      width: 180,
      render: (text) => <Text copyable>{text}</Text>,
    },
    {
      title: '课程信息',
      dataIndex: 'course_title',
      key: 'course_title',
      render: (text, record) => (
        <Space>
          <Avatar 
            shape="square" 
            size={40} 
            src={record.course_cover}
            alt={text}
          />
          <Text ellipsis style={{ maxWidth: 200 }}>{text}</Text>
        </Space>
      ),
    },
    {
      title: '用户',
      dataIndex: 'user_name',
      key: 'user_name',
      render: (text, record) => (
        <Space>
          <Avatar 
            size="small" 
            icon={<UserOutlined />}
            src={record.user_avatar}
          />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      align: 'right',
      render: (amount) => (
        <Text strong>¥{amount !== undefined && amount !== null ? Number(amount).toFixed(2) : '0.00'}</Text>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={statusColors[status]}>
          {statusLabels[status]}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => viewOrderDetail(record.id)}
            title="查看详情"
          />
          {record.status === 'paid' && (
            <Button 
              type="text" 
              danger
              icon={<RollbackOutlined />} 
              onClick={() => handleRefund(record)}
              title="退款"
            />
          )}
        </Space>
      ),
    },
  ];
  
  return (
    <div className="orders-container">
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="stats-row">
        <Col xs={24} sm={12} md={8} lg={4}>
          <Card bordered={false} className="stats-card">
            <Statistic 
              title="总订单数" 
              value={statistics.total_orders} 
              prefix={<FileTextOutlined />}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={4}>
          <Card bordered={false} className="stats-card">
            <Statistic 
              title="已支付订单" 
              value={statistics.paid_orders} 
              prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={4}>
          <Card bordered={false} className="stats-card">
            <Statistic 
              title="退款订单" 
              value={statistics.refunded_orders} 
              prefix={<RollbackOutlined style={{ color: '#f5222d' }} />}
              loading={statsLoading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={4}>
          <Card bordered={false} className="stats-card">
            <Statistic 
              title="总销售额" 
              value={statistics.total_sales} 
              prefix={<DollarOutlined style={{ color: '#1890ff' }} />}
              precision={2}
              loading={statsLoading}
              suffix="元"
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={4}>
          <Card bordered={false} className="stats-card">
            <Statistic 
              title="退款金额" 
              value={statistics.total_refunds} 
              prefix={<DollarOutlined style={{ color: '#f5222d' }} />}
              precision={2}
              loading={statsLoading}
              suffix="元"
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={4}>
          <Card bordered={false} className="stats-card stats-card-highlight">
            <Statistic 
              title="净收入" 
              value={statistics.net_income} 
              prefix={<DollarOutlined />}
              precision={2}
              loading={statsLoading}
              suffix="元"
            />
          </Card>
        </Col>
      </Row>

      <Card bordered={false} className="orders-card">
        <div className="card-title-row">
          <Title level={4}>订单管理</Title>
          <Space>
            <Button 
              icon={<ReloadOutlined />}
              onClick={() => {
                fetchOrders();
                fetchStatistics();
              }}
            >
              刷新
            </Button>
          </Space>
        </div>
        
        <Tabs 
          activeKey={activeKey} 
          onChange={setActiveKey}
          className="order-tabs"
          tabBarStyle={{ marginBottom: 24 }}
          items={[
            {
              key: 'orders',
              label: (
                <span>
                  <TableOutlined />
                  订单列表
                </span>
              ),
              children: (
                <>
                  {/* 筛选器 */}
                  <div className="filter-container">
                    <Space wrap>
                      <Search
                        placeholder="搜索订单号/课程/用户"
                        value={filters.searchTerm}
                        onChange={(e) => handleFilterChange('searchTerm', e.target.value)}
                        onSearch={handleSearch}
                        allowClear
                        style={{ width: 250 }}
                      />
                      <Select
                        placeholder="订单状态"
                        value={filters.status}
                        onChange={(value) => handleFilterChange('status', value)}
                        allowClear
                        style={{ width: 120 }}
                      >
                        <Option value="paid">已支付</Option>
                        <Option value="refunded">已退款</Option>
                      </Select>
                      <RangePicker
                        value={filters.dateRange}
                        onChange={(dates) => handleFilterChange('dateRange', dates)}
                        placeholder={['开始日期', '结束日期']}
                      />
                      <Button onClick={resetFilters}>重置</Button>
                    </Space>
                  </div>
                  
                  {/* 订单表格 */}
                  <Table
                    columns={columns}
                    dataSource={orders}
                    rowKey="id"
                    pagination={pagination}
                    loading={loading}
                    onChange={handleTableChange}
                    scroll={{ x: 1200 }}
                  />
                </>
              ),
            },
            {
              key: 'analytics',
              label: (
                <span>
                  <BarChartOutlined />
                  数据分析
                </span>
              ),
              children: <OrderAnalytics />,
            },
          ]}
        />
      </Card>
      
      {/* 订单详情抽屉 */}
      <Drawer
        className="order-detail-drawer"
        open={detailVisible}
        onClose={closeDetail}
        title={
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: '12px', 
            fontSize: '16px', 
            fontWeight: 500 
          }}>
            订单详情
            {currentOrder && (
              <Tag style={{ 
                marginRight: 0, 
                borderRadius: '4px', 
                padding: '0 8px', 
                height: '22px', 
                lineHeight: '20px', 
                fontSize: '12px' 
              }} 
              color={statusColors[currentOrder.status]}>
                {statusLabels[currentOrder.status] || '未知状态'}
              </Tag>
            )}
          </div>
        }
        width={500}
        headerStyle={{
          borderBottom: '1px solid #f0f0f0',
          padding: '16px 24px'
        }}
        bodyStyle={{
          padding: '16px',
          backgroundColor: '#f9fafb'
        }}
        footerStyle={{
          borderTop: '1px solid #f0f0f0',
          padding: '12px 24px'
        }}
        footer={
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button onClick={closeDetail}>关闭</Button>
          </div>
        }
      >
        {detailLoading ? (
          <div style={{ 
            display: 'flex', 
            justifyContent: 'center', 
            alignItems: 'center', 
            height: '100%', 
            padding: '40px 0' 
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ 
                display: 'inline-block',
                width: '30px', 
                height: '30px', 
                border: '2px solid rgba(24, 144, 255, 0.1)',
                borderTopColor: '#1890ff',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite' 
              }}></div>
              <p style={{ marginTop: '12px', color: 'rgba(0, 0, 0, 0.45)' }}>加载中...</p>
            </div>
          </div>
        ) : currentOrder ? (
          <div style={{ /* detail-container styles */ }}>
            {/* 订单基本信息 */}
            <div style={{ 
              backgroundColor: '#fff', 
              borderRadius: '4px', 
              marginBottom: '16px', 
              padding: '16px', 
              boxShadow: '0 1px 2px rgba(0, 0, 0, 0.03)' 
            }}>
              <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center' 
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <FileTextOutlined style={{ color: '#1890ff' }} />
                  <Text copyable={{ text: currentOrder.order_no }}>
                    {currentOrder.order_no}
                  </Text>
                </div>
                <div style={{ fontSize: '12px' }}>
                  <Text type="secondary">
                    {dayjs(currentOrder.created_at).format('YYYY-MM-DD HH:mm')}
                  </Text>
                </div>
              </div>
            </div>

            {/* 课程信息 */}
            <div style={{ 
              backgroundColor: '#fff', 
              borderRadius: '4px', 
              marginBottom: '16px', 
              padding: '16px', 
              boxShadow: '0 1px 2px rgba(0, 0, 0, 0.03)' 
            }}>
              <div style={{ display: 'flex' }}>
                <div style={{ 
                  width: '100px', 
                  height: '70px', 
                  marginRight: '12px', 
                  borderRadius: '4px', 
                  overflow: 'hidden', 
                  flexShrink: 0 
                }}>
                  <img 
                    alt={currentOrder.course_title} 
                    src={currentOrder.course_cover} 
                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                  />
                </div>
                <div style={{ 
                  flex: 1, 
                  display: 'flex', 
                  flexDirection: 'column', 
                  justifyContent: 'space-between' 
                }}>
                  <div style={{ marginBottom: '4px' }}>
                    <Text strong style={{ 
                      display: '-webkit-box', 
                      WebkitLineClamp: 2, 
                      WebkitBoxOrient: 'vertical', 
                      overflow: 'hidden' 
                    }}>
                      {currentOrder.course_title}
                    </Text>
                  </div>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="danger" style={{ fontSize: '16px' }}>
                      ¥{Number(currentOrder.amount).toFixed(2)}
                    </Text>
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                    <div style={{ 
                      display: 'flex', 
                      alignItems: 'center', 
                      gap: '4px', 
                      fontSize: '12px', 
                      color: 'rgba(0, 0, 0, 0.45)', 
                      marginRight: '8px' 
                    }}>
                      <UserOutlined />
                      <Text>{currentOrder.teacher_name || '未知教师'}</Text>
                    </div>
                    <div style={{ 
                      display: 'flex', 
                      alignItems: 'center', 
                      gap: '4px', 
                      fontSize: '12px', 
                      color: 'rgba(0, 0, 0, 0.45)', 
                      marginRight: '8px' 
                    }}>
                      <CalendarOutlined />
                      <Text>{currentOrder.booking_date || '未设置日期'}</Text>
                    </div>
                    <div style={{ 
                      display: 'flex', 
                      alignItems: 'center', 
                      gap: '4px', 
                      fontSize: '12px', 
                      color: 'rgba(0, 0, 0, 0.45)' 
                    }}>
                      <ClockCircleOutlined />
                      <Text>{currentOrder.time_slot || '未设置时间'}</Text>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 支付信息 */}
            <div style={{ 
              backgroundColor: '#fff', 
              borderRadius: '4px', 
              marginBottom: '16px', 
              padding: '16px', 
              boxShadow: '0 1px 2px rgba(0, 0, 0, 0.03)' 
            }}>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '8px', 
                marginBottom: '16px', 
                fontSize: '15px' 
              }}>
                <DollarOutlined style={{ color: '#1890ff' }} />
                <Text strong>支付信息</Text>
              </div>
              <div>
                <div style={{ display: 'flex', marginBottom: '8px' }}>
                  <Text type="secondary" style={{ width: '80px', flexShrink: 0 }}>支付方式：</Text>
                  <Text>{paymentMethodLabels[currentOrder.payment_method] || '未知'}</Text>
                </div>
                {currentOrder.transaction_id && (
                  <div style={{ display: 'flex', marginBottom: '8px' }}>
                    <Text type="secondary" style={{ width: '80px', flexShrink: 0 }}>交易号：</Text>
                    <Text copyable>{currentOrder.transaction_id}</Text>
                  </div>
                )}
                {currentOrder.status === 'refunded' && (
                  <>
                    <div style={{ display: 'flex', marginBottom: '8px' }}>
                      <Text type="secondary" style={{ width: '80px', flexShrink: 0 }}>退款金额：</Text>
                      <Text type="danger">
                        ¥{currentOrder.refund_amount !== undefined && currentOrder.refund_amount !== null 
                          ? Number(currentOrder.refund_amount).toFixed(2) 
                          : '0.00'}
                      </Text>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '8px' }}>
                      <Text type="secondary" style={{ width: '80px', flexShrink: 0 }}>退款原因：</Text>
                      <Text>{currentOrder.refund_reason || '未提供'}</Text>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '8px' }}>
                      <Text type="secondary" style={{ width: '80px', flexShrink: 0 }}>退款时间：</Text>
                      <Text>{currentOrder.refunded_at ? dayjs(currentOrder.refunded_at).format('YYYY-MM-DD HH:mm') : '未记录'}</Text>
                    </div>
                  </>
                )}
              </div>
            </div>

            {/* 用户信息 */}
            <div style={{ 
              backgroundColor: '#fff', 
              borderRadius: '4px', 
              padding: '16px', 
              boxShadow: '0 1px 2px rgba(0, 0, 0, 0.03)' 
            }}>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '8px', 
                marginBottom: '16px', 
                fontSize: '15px' 
              }}>
                <UserOutlined style={{ color: '#1890ff' }} />
                <Text strong>用户信息</Text>
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                  <Avatar
                    size="small"
                    icon={<UserOutlined />}
                    src={currentOrder.user_avatar}
                  />
                  <Text>{currentOrder.user_name || '未知用户'}</Text>
                </div>
                <div style={{ display: 'flex', marginBottom: '8px' }}>
                  <Text type="secondary" style={{ width: '80px', flexShrink: 0 }}>联系电话：</Text>
                  <Text>{currentOrder.user_phone || currentOrder.contact_phone || '未提供'}</Text>
                </div>
                {currentOrder.contact_name && currentOrder.contact_name !== currentOrder.user_name && (
                  <div style={{ display: 'flex', marginBottom: '8px' }}>
                    <Text type="secondary" style={{ width: '80px', flexShrink: 0 }}>联系人：</Text>
                    <Text>{currentOrder.contact_name}</Text>
                  </div>
                )}
              </div>
            </div>
          </div>
        ) : (
          <div style={{ 
            display: 'flex', 
            justifyContent: 'center', 
            alignItems: 'center', 
            height: '300px', 
            color: 'rgba(0, 0, 0, 0.25)' 
          }}>
            暂无订单详情
          </div>
        )}
      </Drawer>
      
      {/* 退款处理模态框 */}
      <Modal
        title="订单退款处理"
        open={refundModalVisible}
        onCancel={() => setRefundModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setRefundModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            danger
            loading={refundLoading}
            onClick={showRefundConfirm}
          >
            确认退款
          </Button>,
        ]}
      >
        <Form
          form={refundForm}
          layout="vertical"
        >
          <Form.Item
            name="refund_amount"
            label="退款金额"
            rules={[
              { required: true, message: '请输入退款金额' },
              { type: 'number', min: 0.01, message: '退款金额必须大于0' },
              { 
                type: 'number', 
                max: currentOrder?.amount ? Number(currentOrder.amount) : 0, 
                message: '退款金额不能超过订单金额' 
              },
            ]}
          >
            <InputNumber 
              placeholder="请输入退款金额" 
              style={{ width: '100%' }}
              precision={2}
              addonBefore="¥"
            />
          </Form.Item>
          
          <Form.Item
            name="refund_reason"
            label="退款原因"
            rules={[{ required: true, message: '请输入退款原因' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入退款原因" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Orders; 